package org.lifeaddict.sybill;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataSource {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_lvName, MySQLiteHelper.COLUMN_lvLocation, 
			MySQLiteHelper.COLUMN_lvDay, MySQLiteHelper.COLUMN_lvDate, 
			MySQLiteHelper.COLUMN_lvTime };

	public DataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public DetailInfo createDetail(String lvName, String lvLocation, 
			String lvDay, String lvDate, String lvTime) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_lvName, lvName);
		values.put(MySQLiteHelper.COLUMN_lvLocation, lvLocation);
		values.put(MySQLiteHelper.COLUMN_lvDay, lvDay);
		values.put(MySQLiteHelper.COLUMN_lvDate, lvDate);
		values.put(MySQLiteHelper.COLUMN_lvTime, lvTime);
		long insertId = database.insert(MySQLiteHelper.TABLE_LVS, null,values);
		Cursor cursor = database.query(MySQLiteHelper.TABLE_LVS,
				allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		DetailInfo newDetail = cursorToDetail(cursor);
		cursor.close();
		return newDetail;
	}

	public void deleteDetail(DetailInfo detail) {
		long id = detail.getId();
		System.out.println("LV deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_LVS, MySQLiteHelper.COLUMN_ID
				+ " = " + id, null);
	}
	
	public void deleteAll() {
		database.delete(MySQLiteHelper.TABLE_LVS, null, null);
	}

	public ArrayList<DetailInfo> getAllDetails() {
		ArrayList<DetailInfo> details = new ArrayList<DetailInfo>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_LVS,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			DetailInfo detail = cursorToDetail(cursor);
			details.add(detail);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return details;
	}

	private DetailInfo cursorToDetail(Cursor cursor) {
		DetailInfo detail = new DetailInfo();
		detail.setId(cursor.getLong(0));
		detail.setName(cursor.getString(1));
		detail.setLocation(cursor.getString(2));
		detail.setDay(cursor.getString(3));
		detail.setDate(cursor.getString(4));
		detail.setTime(cursor.getString(5));
		return detail;
	}
} 